﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.Persistent;
using System.Data;
using Jumpton.Data;
using Jumpton.SFA.Server.Entity;

namespace Jumpton.SFA.Server.BusinessRule.InStoreDataMeasures
{
    public class CPR_ConfigManager:BusinessLogic
    {
        public CPR_Config Load(decimal ID)
        {
            return (CPR_Config)ObjectRow.Load(typeof(CPR_Config), string.Format("this.ID={0}", ID));
        }

        public CPR_Config LoadName(string MeasurementName,decimal domainid)
        {
            return (CPR_Config)ObjectRow.Load(typeof(CPR_Config), string.Format("this.MeasurementName='{0}' and DomainID='{1}'", MeasurementName, domainid));
        }

        public CPR_Config LoadSequence(string Sequence, decimal domainid)
        {
            return (CPR_Config)ObjectRow.Load(typeof(CPR_Config), string.Format("this.Sequence='{0}' and DomainID='{1}'", Sequence,domainid));
        }

        public ObjectTable GetCPR_ConfigTable(decimal domainid)
        {
            StringBuilder sb = new StringBuilder();// ("this.IsActive = 'True' ");
            if (domainid > 0)
            {
                sb.AppendFormat(" this.DomainID='{0}' ORDER BY Sequence ASC", domainid);
            }

            return new ObjectTable(typeof(CPR_Config), sb.ToString().TrimStart('a', 'n', 'd'));
        }

        public void CPR_ConfigCreateTable(string ValueType, string TableName)
        {
            SqlData.ExecuteSP("SP_CreateCustomTable", ValueType, TableName);
        }

        public bool Save(CPR_Config cpr)
        {
            try
            {
                cpr.Connection.BeginTransaction(null);

                cpr.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                if (cpr.State == DataRowState.Added)
                {
                    
                    cpr.TableName = "CPR_" + Guid.NewGuid();
                    CPR_ConfigCreateTable(cpr.ValueType, cpr.TableName);
                }
                cpr.Save();
                cpr.Connection.CommitTransaction();

                return true;
            }
            catch (Exception ex)
            {
                cpr.Connection.RollbackTransaction();
                this.message = ex.Message;
                throw ex;
            }
        }
    }
}
